/*
 * Created on 23.07.2008
 *
 */
package com.appspot.yttv.client;

import com.google.gwt.core.client.GWT;
import com.google.gwt.user.client.ui.ChangeListener;
import com.google.gwt.user.client.ui.ChangeListenerCollection;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.SourcesChangeEvents;

/**
 * 
 * @author Uwe Maurer
 *
 */
public class PlaylistPlayer extends ChromelessPlayer implements SourcesChangeEvents  {
	
	private  Playlist playlist = new Playlist();
	private final Label title;
	private final ChangeListenerCollection changeListeners = new ChangeListenerCollection();
	private int pos = -1;
	private Video currentVideo;
	private boolean loadingNewVideo = false;

	public PlaylistPlayer(String name, Label title) {
		super(name);
		this.title = title;
	}
	
	private Video nextVideo() {
		if (playlist.getVideos().size() ==0) {
			return null;
		}
		pos = (pos + 1) % playlist.getVideos().size();
		currentVideo =  playlist.getVideos().get(pos);
		return currentVideo;
	}

	public Video getCurrentVideo() {
		return currentVideo;
	}
	
	public void playNext() {
		Video video = nextVideo();
		loadVideo(video);
	}

	public void playVideo(Video video) {
		int position = 0;
		for (Video v : playlist.getVideos()) {
			if (v.equals(video)) {
				pos = position;
				break;
			}
			position++;
		}
		currentVideo = video;
		loadVideo(video);
	}
	
	private  void loadVideo(Video video) {
		loadingNewVideo = true;
		loadVideoById(video.getId(), 0);
		loadingNewVideo = false;
		if (title != null) {
			title.setText(video.getTitle());
		}
		changeListeners.fireChange(this);
	}
	
	public void setPlaylist(Playlist playlist) {
		this.playlist = playlist;
		pos = -1;
	}	
	
	@Override
	protected void onLoad() {
		createSwf(537, 400, new PlayerListener() {

			public void onReady() {
				if (GWT.isScript() == false) {
					//  turn sound off during development
					setVolume(80);
				} else {
					setVolume(80);
				}
				playNext();
			}

			public void onStateChange(PlayerState state) {
				if (state == PlayerState.STOPPED  && !loadingNewVideo) {
					playNext();
				}
			}
		});

	}
	
	public void addChangeListener(ChangeListener listener) {
		changeListeners.add(listener);
	}

	public void removeChangeListener(ChangeListener listener) {
		changeListeners.remove(changeListeners);
	}

}
